%%% Written by  Daniel Lewis, 2020, for "Robust Inference in Models 
%%% Identified via Heteroskedasticity", Review of Economics and Statistics.
%
% This file computes the first-stage F-statistic for the 2-variable "simple
% case" model where only the variance of the shock of interest is assumed 
% to change across regimes. It takes as inputs innovations for each regime
% and outputs the first-stage heteroskedasticity-robust F-statistic. As
% optional outputs it also reports the level of bias at which weak
% identification can be rejected based on the critical values of Montiel
% & Pflueger (2013).
%
% Inputs:
% eta21: time series for regime 1 of the innovation normalized to have unit 
% loading on the shock of interest. It is assumed that the shock of
% interest's variance changes while the other shock's variance remains 
% constant. This is the series eta_{2t} for regime C in the paper. 
% eta22: time series for regime 2 of the innovation normalized to have unit
% loading on the shock of interest. This is the series eta_{2t} for regime 
% P in the paper. 

function [Fstat, reject]=WeakHetFirstF_upd(eta21,eta22)
T1=length(eta21); % Compute number of observations in each regime
T2=length(eta22);
T=T1+T2; % Total observations
eta=[eta21-mean(eta21,1);eta22-mean(eta22,1)]; % Demean the data (the model assumes eta is mean zero in each subsample) and put the innovations together
Z=[repmat(-T/T1,T1,1);repmat(T/T2,T2,1)].*eta; % construct instrument
[b,~,r]=regress(eta,Z); % first stage
varb=T*mean((Z.*r).^2)/sum(Z.^2)^2;  % heteroskedasticity-robust asymptotic variance
Fstat=b^2/varb; % F-statistic
fprintf('Het. Id. First-stage F-stat = %.2f\n',Fstat);
if nargout>1
    rej=Fstat>[37.42 23.11 15.06 12.05];
    biases=[.05 .1 .2 .3];
    rej=find(rej,1,'first');
    if isempty(rej)
        reject='Weak identification not rejected for any bias level';
        fprintf('Weak identification not rejected for any bias level');
        
    else
        reject=biases(rej);
        fprintf('Minimum bias level of rejection = %.2f\n',reject);
    end
end
end
